﻿namespace LogManager.Core.Models
{
    using LogManager.Core;
    using LogManager.Utils.Unity;
    using LogManager.Utils.Xml;
    using System.Xml.Linq;

    public class Location : XmlElementBase, ILocation
    {
        public const string DEFAULT_TEMPLATE = @"<Location LogType=""File"" Name=""Location Name"">d$\Path\To\Folder</Location>";

        public virtual string Name { get; set; }
        public virtual LogFileType LogType { get; set; }
        public virtual string Path { get; set; }
        public IServer ParentServer { get; private set; }

        public Location(XElement baseNode, IServer parentServer)
            : base(baseNode)
        {
            ParentServer = parentServer;
            this.Initialize();
            this.PropertyChanged += (a, b) => SaveChanges();
        }

        private void Initialize()
        {
            var xml = new XmlResolver<Location>(BaseNode);
            this.Name = xml.GetAttributeValue(c => c.Name);
            this.LogType = xml.GetAttributeValue(c => c.LogType);
            this.Path = BaseNode.Value;
        }

        public override void SaveChanges()
        {
            var xml = new XmlResolver<Location>(BaseNode);
            xml.SetAttributeValue(c => c.Name, Name);
            xml.SetAttributeValue(c => c.LogType, LogType);
            BaseNode.Value = this.Path;
        }

        public void DeleteLocation()
        {
            this.ParentServer.Locations.Remove(this);
        }

        [DependsUpon("Path")]
        public string FullPathSource
        {
            get { return "\\\\" + this.ParentServer.Ip + "\\" + this.Path; }
        }

        [DependsUpon("Name")]
        public string FullPathDestination
        {
            get
            {
                return
                     "\\\\" + this.ParentServer.ParentPlateform.ParentWarehouse.Ip +
                     "\\" + this.ParentServer.ParentPlateform.Depository +
                    "\\" + this.ParentServer.ParentPlateform.Name +
                    "\\" + this.ParentServer.Name +
                    "\\" + this.Name;
            }
        }
    }
}
